#DESCRIPTION:
#Kinematic analysis of geologic structures vis-a-vis slopes


#1. libraries and modules

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import beta,gamma,gaussian_kde, kstest, ks_2samp, ttest_ind,norm
import matplotlib.cm as cm

import BartonBandis as BB
import Kinematic_analysis as KA
import generic_stereo_plotting as stplt
import base_maps as bm


def add_subplot_axes(ax,rect,axisbg='w'):
    fig = plt.gcf()
    box = ax.get_position()
    
    width = box.width
    height = box.height
    print box,width,height
    inax_position  = ax.transAxes.transform(rect[0:2])
    transFigure = fig.transFigure.inverted()
    infig_position = transFigure.transform(inax_position)
    print infig_position
    print inax_position
    x = infig_position[0]
    y = infig_position[1]
    width *= rect[2]
    height *= rect[3]  # <= Typo was here
    subax = fig.add_axes([x,y,width,height],axisbg=None,frameon=None)
    return subax




    
    

#MAIN


#inputs
path_to_file='/home/eglsais/Dropbox/Thesis/csv_files_originals/'
Li_list=[1,2,3,4,5]
Li_label_List=['CCw','CCe','FC','LS','UM']
Li_uw=np.asarray([24,24,24,25,28]) #KN/m3
df_GA=pd.read_csv(path_to_file+'DF_el_li_gr_asp',index_col=0)
df_disc=pd.read_csv(path_to_file+'geologic_structures',sep=',',index_col=0)

#generate basemap
basemap=bm.generate_basemap(1)

#prepare figures and axes
fig,ax=plt.subplots(nrows=len(Li_list),ncols=len(df_disc),
                    sharex=True,sharey=True)
mapfig,mapax=plt.subplots(nrows=2,ncols=4,
                    sharex=True,sharey=True)

for j in range(8):#len(df_disc)):
    plt.sca(mapax[j/4,j-(j/4)*4])
    bm.plot_basemap(1,basemap)




    
for i in range(len(Li_list)):
    
    cur_df_GA=df_GA[df_GA.Li==Li_list[i]]

    #1.1 generating random indices of slope data to plot
    df_toplot=cur_df_GA
    samp_size=500
    r_indx=np.arange(len(df_toplot))
    np.random.shuffle(r_indx)
    r_indx=r_indx[:samp_size]
    
    for j in range(6,len(df_disc)):
        print i,j
        cur_df_disc=df_disc[df_disc.index==j+1]
        d_dip,d_ddir=cur_df_disc.dip.values,cur_df_disc.ddir.values

        applicable_to_lith=cur_df_disc[Li_label_List[i]].values

        if applicable_to_lith!=1: continue

        #conduct kinematic analysis for given discontinuity
        cur_df_GA=KA.KinematicAnalysis(cur_df_GA,d_dip, d_ddir)

        #selecting rows for FS analysis (where KA==1)
        KA_cur_df_GA=cur_df_GA[(cur_df_GA.KA==1)]

        ####################################
        #conduct BB FS analysis

        #defining constants
        uw=Li_uw[i]*10**-3 #MN/m3
        base=30
        Ln=.5

        #defining slope gradient (beta) and discontinuity dip (alpha)
        beta=KA_cur_df_GA.grad.values
        alpha=d_dip*np.ones(len(KA_cur_df_GA))#KA_cur_df_GA.d_adip.values

        #defining random variables
        numrand=1000
        sign_min,sign_max=0.,3.     #MPa
        phir_min,phir_max=10,25     #degrees
        JRC0_min,JRC0_max=0,20     
        JCS0_min,JCS0_max=10,60     #MPa

        sig_n,phi_r,JRC0,JCS0=BB.generate_random_BB_vars(sign_min,sign_max,
                                                      phir_min,phir_max,
                                                      JRC0_min, JRC0_max,
                                                      JCS0_min,JCS0_max,
                                                      numrand)

        df_BBFS=BB.BB_stability_analysis(uw,base,Ln,
                                  beta,alpha,
                                  phi_r,JRC0,JCS0,0)

        KA_cur_df_GA['FS_mean']=df_BBFS.FS_mean.values
        KA_cur_df_GA['FS_std']=df_BBFS.FS_std.values
        KA_cur_df_GA['FS_pcF']=df_BBFS.FS_pcF.values

        ############################################################

        #0 setting current axis
        plt.sca(ax[i,j])
        stplt.plot_stereonet()
        
        #1. plotting random slope data
        df_toplot=cur_df_GA
        stplt.plot_data(df_toplot.grad.values[r_indx],df_toplot.asp.values[r_indx],1,'.')
        
        #2. plotting kinematically admissible slope data
        df_toplot=KA_cur_df_GA
        stplt.plot_colorvalue_data(df_toplot.grad.values,df_toplot.asp.values,df_toplot.FS_pcF.values,0,100,10)
        
        #3. drawing great circle representing current discontinuity
        stplt.draw_great_circle(d_dip,d_ddir,'r',1.5)

        #4. writing data as text in plot
##        pcKA=len(KA_cur_df_GA)*100/(len(cur_df_GA)*1.)
##        meanpcF=np.mean(KA_cur_df_GA.FS_pcF.values)
##        plt.text(0.8,0.8,'%KA: '+str(round(pcKA,3))+"\n"+"mean %failure: "+str(round(meanpcF,1)))

        #5. plotting data on map
        bm.plot_on_basemap(KA_cur_df_GA,basemap.shape[1],0,100,2,.1)
        
        
       


fig.tight_layout()
mapfig.tight_layout()


#inset stereoplot for map
for j in range(6,len(df_disc)):
    j=j-6
    cur_df_disc=df_disc[df_disc.index==j+1]
    d_dip,d_ddir=cur_df_disc.dip.values,cur_df_disc.ddir.values
    plt.sca(mapax[j/4,j-(j/4)*4])
    inset_ax=add_subplot_axes(plt.gca(),[0.05,0.05,0.3,0.3],axisbg='w')
    plt.sca(inset_ax)
    stplt.plot_stereonet()
    stplt.draw_great_circle(d_dip,d_ddir,'r',1.5)
    plt.title(cur_df_disc.desc.values[0],fontsize='small')
    

plt.show()
        
  
